import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout/indexView.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userInfo.vue')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCate.vue')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList.vue')
      }
    ]
  },
  {
    path: '/reg',
    component: () => import('@/views/resgister/indexView.vue')
  },
  {
    path: '/login',
    component: () => import('@/views/login/indexView.vue')
  },
  {
    path: '/test',
    component: () => import('@/views/test.vue')
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/reg'] // 白名单
// 无需登录就可以访问的地址
// 全局前置路由守卫
// 浏览器第一次打开页面会触发一次
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (!store.state.userInfo.username) {
      store.dispatch('getUserInfoAction')
    }
    next()
  } else {
    // 未登录,
    // next()强制切换路由地址，会再次触发路由守卫
    // .includes判断值是否在数组里出现过，出现返回true
    if (whiteList.includes(to.path)) {
      // 未登录,如果在白名单中，是可以访问的路由地址,则放行
      next()
    } else {
      // next()强制切换到登录路径上
      next('/login')
    }
  }
})

export default router
